//
//  LocationViewController.m
//  Hui
//
//  Created by HawkingWang on 16/10/27.
//  Copyright © 2016年 Hui. All rights reserved.
//

#import "LocationViewController.h"
#import "NearbyTableViewCell.h"//附近cell
#import "SearchAddressViewController.h"//搜索Controller
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import "MyAnnotationView.h"

@interface LocationViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, BMKMapViewDelegate,BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>
/**搜索*/
@property (weak, nonatomic) IBOutlet UITextField *searchAddress;
@property (weak, nonatomic) IBOutlet UILabel *searchLabel;
@property (weak, nonatomic) IBOutlet UIView *searchbgView;
/**地图*/
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
/**附近*/
@property (weak, nonatomic) IBOutlet UIView *nearbyView;
@property (weak, nonatomic) IBOutlet UITableView *nearbyTableView;


@end

@implementation LocationViewController
{
    BMKLocationService *_locationService;
    BMKPointAnnotation *_annotation;
    MyAnnotationView *_annoView;
    BMKGeoCodeSearch *_searcher;
}

 static NSString *const NearbyTableViewCellID = @"NearbyTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _searchbgView.layer.borderWidth = 1;
    _searchbgView.layer.borderColor = RGBCOLOR(226, 235, 241).CGColor;
    _searchAddress.delegate = self;
    [_nearbyTableView registerNib:[UINib nibWithNibName:@"NearbyTableViewCell" bundle:nil] forCellReuseIdentifier:NearbyTableViewCellID];
    
    //地图
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    _mapView.showsUserLocation = YES;
    _mapView.zoomLevel = 17;
    _mapView.delegate = self;
    _mapView.mapType = BMKMapTypeStandard;
    _mapView.overlookEnabled = NO;
    _mapView.rotateEnabled = NO;
    //定位
    _locationService = [[BMKLocationService alloc]init];
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    
    
    //初始化检索对象
    _searcher =[[BMKGeoCodeSearch alloc]init];
    _searcher.delegate = self;
    
    _annotation = [[BMKPointAnnotation alloc] init];
    // 创建大头针
    _annoView = [MyAnnotationView annotationViewWithMap:_mapView];
    // 设置模型
    _annoView.myImage = [UIImage imageNamed:@"map-point"];
    _annoView.annotation = _annotation;
    [_mapView addAnnotation:_annotation];
}

#pragma mark === BaiduSDKDelegate ===
#pragma mark === 处理方向变更信息 ===
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
}
#pragma  mark === 处理位置坐标更新 ===
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    CLLocationCoordinate2D user_coordinate = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    //设置中心点
    //更新数据
    [_mapView updateLocationData:userLocation];
    _mapView.centerCoordinate = user_coordinate;
//    if ([_model.x isKindOfClass:[NSNull class]]) {
//        _mapView.centerCoordinate = user_coordinate;
//    }else{
//        CLLocationCoordinate2D coordinate;
//        coordinate.latitude = [_model.y doubleValue];
//        coordinate.longitude = [_model.x doubleValue];
//        _mapView.centerCoordinate = coordinate;
//        _annotation.coordinate = coordinate;
//    }
    [_locationService stopUserLocationService];
    
    
    
}
#pragma mark === 大头针 ===
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        if (!_annoView) {
            // 创建大头针
            _annoView = [MyAnnotationView annotationViewWithMap:mapView];
            // 设置模型
            _annoView.myImage = [UIImage imageNamed:@"map-point"];
            _annoView.annotation = annotation;
        }
        return _annoView;
    }
    return nil;
}
#pragma mark === 地图点击 设置大头针位置 ===
//点中底图标注
- (void)mapView:(BMKMapView *)mapView onClickedMapPoi:(BMKMapPoi*)mapPoi;{
    [self getAnnotationAddressWithCoordinate:mapPoi.pt];
    
    [SVProgressHUD show];
    _annotation.coordinate = mapPoi.pt;
    [_mapView addAnnotation:_annotation];
    
//    mapPoi.text
}
//点中底图空白处
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate{
    [self getAnnotationAddressWithCoordinate:coordinate];
    
    [SVProgressHUD show];
    _annotation.coordinate = coordinate;
    [_mapView addAnnotation:_annotation];
}

#pragma mark === 反向地理编码检索 ===
- (void)getAnnotationAddressWithCoordinate:(CLLocationCoordinate2D)coordinate{
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc] init];
    reverseGeoCodeSearchOption.reverseGeoPoint = coordinate;
    BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
    reverseGeoCodeSearchOption = nil;
    if (flag)
    {
                    NSLog(@"反geo检索发送成功");
        
    }
    else
    {
                    NSLog(@"反geo检索发送失败");
        [SVProgressHUD dismiss];
    }
}
#pragma mark === 反向地理检索回调 ===
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error;{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        //        _address.text = result.address;
                NSLog(@"%@", result.address);
    }
    else {
                NSLog(@"抱歉，未找到结果");
    }
    [SVProgressHUD dismiss];
}

#pragma mark === 地理编码检索 ===
- (void)getCoordinateWithCity:(NSString *)city  AndAddress:(NSString *)address{
    BMKGeoCodeSearchOption *geoCodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    geoCodeSearchOption.city = city;
    geoCodeSearchOption.address = address;
    
    BOOL flag = [_searcher geoCode:geoCodeSearchOption];
    geoCodeSearchOption = nil;
    if(flag)
    {
                NSLog(@"geo检索发送成功");
    }
    else
    {
                NSLog(@"geo检索发送失败");
        [SVProgressHUD dismiss];
    }
}
#pragma mark === 地理检索回调 ===
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        _annotation.coordinate = result.location;
        [_mapView setCenterCoordinate:result.location];
       
    }
    else {
        //        NSLog(@"抱歉，未找到结果, 请手动定位");
    }
    [SVProgressHUD dismiss];
}


#pragma mark === TableViewDelegate ===
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NearbyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NearbyTableViewCellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


#pragma mark === UITextFieldDelegate ===
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    _searchLabel.hidden = YES;
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if ([textField.text isEqualToString:@""]) {
        _searchLabel.hidden = NO;
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_searchAddress resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_searchAddress resignFirstResponder];
    SearchAddressViewController *search = [[SearchAddressViewController alloc] init];
    search.searchString = textField.text;
    
    //周边模糊查询
    
    
    [self.navigationController pushViewController:search animated:YES];
    return YES;
}

- (IBAction)back:(id)sender {
    [_locationService stopUserLocationService];
    _mapView.showsUserLocation = NO;
    _locationService.delegate = nil;
    _mapView.delegate = nil;
    _searcher.delegate = nil;
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
